package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.Voucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IVoucherService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;


    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RedissonClient redissonClient2;

    @Resource
    private RedissonClient redissonClient3;




    @Override
    public Result seckillVoucher(Long voucherId) {
        //查询优惠券
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        if (voucher == null) {
            return Result.fail("抢购失败，请重试！");
        }
        //判断秒杀是否开始
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            //秒杀尚未开始
            return Result.fail("秒杀活动尚未开始！");
        }
        //判断秒杀是否结束
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            //秒杀已经结束
            return Result.fail("秒杀活动已经结束！");
        }
        //判断库存是否充足
        if (voucher.getStock() < 1) {
            //库存不足
            return Result.fail("库存不足！");
        }
        Long userId = UserHolder.getUser().getId();
        //先提交事物，再释放锁
        //synchronized (userId.toString().intern()) {
        //this调用的是原对象而非代理对象，会导致事物失效
        //两种解决方案：1.在当前方法上加入事物，并设置事物传播行为为有则加入
        //2.当前做法：获取代理对象，通过代理对象调用(启动类上要加注解)
        //创建分布式锁对象
        //SimpleRedisLock simpleRedisLock = new SimpleRedisLock(redisTemplate, "order:" + userId);
        RLock lock1 = redissonClient.getLock("lock:order:" + userId);
        RLock lock2 = redissonClient2.getLock("lock:order:" + userId);
        RLock lock3 = redissonClient3.getLock("lock:order:" + userId);
        RLock lock = redissonClient.getMultiLock(lock1, lock2, lock3);
        //获取锁
        //boolean isLock = simpleRedisLock.trylock(100);
        boolean isLock = lock.tryLock();
        //判断是否成功
        if (!isLock) {
            //一人一单，快速失败
            return Result.fail("该类型优惠券每个用户限购一次！");
        }

        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucher);
        } catch (IllegalStateException e) {
            log.info("代理对象执行createVoucherOrder方法失败");
            throw new RuntimeException(e);
        } finally {
            //simpleRedisLock.unlock();
            lock.unlock();
        }
        //}
    }

    @Transactional(rollbackFor = Exception.class)
    public Result createVoucherOrder(SeckillVoucher voucher) {
        //一人一单
        //查询订单
        Long userId = UserHolder.getUser().getId();
        //这里需要值比较，而非对象比较   intern方法会优先从字符串常量池中查找，找到则返回该对象
        //对象锁没有加在这里是因为有可能释放锁之后事物还未提交，从而导致并发安全问题
        //synchronized (userId.toString().intern()) {
        int count = this.lambdaQuery().eq(VoucherOrder::getUserId, userId)
                .eq(VoucherOrder::getVoucherId, voucher.getVoucherId())
                .count();
        //判断是否存在
        if (count > 0) {
            //该用户已经购买过了同类型优惠券
            return Result.fail("该类型优惠券每个用户限购一次！");
        }
        //扣减库存
        //这里可以通过stock>0来实现乐观锁，得益于MySQL的行锁
        boolean success = seckillVoucherService.lambdaUpdate()
                .eq(SeckillVoucher::getVoucherId, voucher.getVoucherId())
                .gt(SeckillVoucher::getStock, 0)
                .set(SeckillVoucher::getStock, voucher.getStock() - 1).update();
        if (!success) {
            return Result.fail("库存不足！");
        }
        //创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        //订单id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        // 用户id
        voucherOrder.setUserId(userId);
        //代金券id
        voucherOrder.setVoucherId(voucher.getVoucherId());
        this.save(voucherOrder);
        //返回订单
        return Result.ok(orderId);
        //}
    }
}
